import {Promise} from 'es6-promise';
import PWSApp from "../../core/app";
import HomeBaseAction from "./act.base";
import {Magics} from "../../core/magics";
import {Request, Response} from "express";
import * as utils from '../../core/utils';
import {RouteType} from "../../core/defines";
import {ErrCode} from "../../core/error.code";
import {MongoColls} from "../../config/mongo";
import UserModel, {
    UserInfo, LoginType,
} from "../../models/mod.user";
declare function require(name: string): any;

export default class UserAction extends HomeBaseAction {
    private _userMod: UserModel;

    constructor(app: PWSApp) {
        super(app);
        this._userMod = new UserModel(this.db.collection(MongoColls.USER));
    }

    name() {
        return `${this.app.name}UserAction`;
    }

    protected _setRoutes() {
        this._setRoot('/api');
        this._route(RouteType.POST, '/login', this._actDoLogin);

        // this._route(RouteType.GET, '/register', this._actRegister);
        // this._route(RouteType.POST, '/register', this._actDoRegister);
        // this._route(RouteType.POST, '/login', this._actDoLogin);
        // this._route(RouteType.GET, '/logout', this._actLogout);
        // this._route(RouteType.POST, '/resetpwd', this._actDoResetPwd);
    }

    private _actDoLogin(req: Request, res: Response) {
        let {wechat, nickName} = req.body;

        let user: UserInfo;
        Promise.resolve().then(() => {
            if (!wechat && !nickName) {
                return Promise.reject({err_code: ErrCode.ArgsMissing});
            }
            return this._userMod.checkExist({wechat});
        }).then((result: UserInfo) => {
            if (result) {
                user = result;
                return ;
            }
            user = {
                wechat,
                _id: utils.objectId(),
                nick_name: nickName
            };
            return this._userMod.createUser(user);
        }).then(() => {
            req.session[Magics.SessUser] = user;
            res.send({err_code: ErrCode.Success});
        }).catch((err: any) => {
            this._errHandler(req, res, err);
        });
    }

    // private _actRegister(req: Request, res: Response) {
    //     Promise.resolve().then(() => {
    //         return this._regionModel.getAllProvinces();
    //     }).then((provinces: Array<Object>) => {
    //         let result = {
    //             prov: provinces
    //         };
    //         res.send(result);
    //     }).catch((err: any) => {
    //         this._errHandler(req, res, err);
    //     });
    // }
    //
    // private _actDoRegister(req: Request, res: Response) {
    //     Promise.resolve().then(() => {
    //         let {wechat} = req.body;
    //         if (wechat) {
    //             let keys = ['wechat', 'nick_name'];
    //             return this._registerByWechat(utils.pick(req.body, keys));
    //         }
    //         let keys = ['name', 'phone', 'prov', 'city', 'dist', 'addr', 'sex', 'password', 'nick_name'];
    //         return this._registerByPhone(utils.pick(req.body, keys));
    //     }).then(() => {
    //         res.send({err_code: ErrCode.Success});
    //     }).catch((err: any) => {
    //         this._errHandler(req, res, err);
    //     });
    // }
    //
    // private _registerByWechat(info: UserBaseInfo): Promise<any> {
    //     let {wechat} = info;
    //     if (!wechat) {
    //         return Promise.reject({err_code: ErrCode.ArgsInvalid});
    //     }
    //     return this._userMod.checkExist({wechat}).then((result) => {
    //         if (result) {
    //             return Promise.reject({err_code: ErrCode.UserExisted});
    //         }
    //         return this._userMod.createUser(info);
    //     });
    // }
    //
    // private _registerByPhone(info: UserBaseInfo): Promise<any> {
    //     let {name, phone, prov, city, dist, addr, sex, password, nick_name} = info;
    //     let invalid = !name || !utils.isPhone(phone) || !utils.isObject(prov)
    //         || !utils.isObject(city) || !utils.isObject(dist) || !addr || !utils.isNumeric(sex) || !password || !nick_name;
    //     if (invalid) {
    //         return Promise.reject({err_code: ErrCode.ArgsInvalid});
    //     }
    //     return this._userMod.checkExist({phone}).then((result) => {
    //         if (result) {
    //             return Promise.reject({err_code: ErrCode.UserExisted});
    //         }
    //         info.password = utils.passwdHash(password);
    //         return this._userMod.createUser(info);
    //     });
    // }
    //
    // private _actDoLogin(req: Request, res: Response) {
    //
    //     let {wechat, phone, password} = req.body;
    //     Promise.resolve().then(() => {
    //         if (!wechat && !(phone && password)) {
    //             return Promise.reject({err_code: ErrCode.ArgsMissing});
    //         }
    //
    //         let filter = {};
    //         if (phone) {
    //             filter['phone'] = phone;
    //         }
    //         if (wechat) {
    //             filter['wechat'] = wechat;
    //         }
    //
    //         return this._userMod.checkExist(filter);
    //     }).then((user: Object) => {
    //         if (!user) {
    //             return Promise.reject({err_code: ErrCode.UserNotFound});
    //         }
    //         if (phone && utils.passwdHash(password) != user['password']) {
    //             return Promise.reject({err_code: ErrCode.UserPasswdErr});
    //         }
    //
    //         req.session[Magics.SessUser] = {
    //             _id: user['_id'],
    //             name: user['name'],
    //             phone: user['phone'],
    //             wechat: user['wechat'],
    //             prov: user['prov'],
    //             city: user['city'],
    //             dist: user['dist'],
    //             addr: user['addr'],
    //             sex: user['sex'],
    //             nick_name: user['nick_name']
    //         };
    //         req.session[Magics.SessUser].login_type = phone ? LoginType.phone : LoginType.wechat;
    //
    //         res.send({err_code: ErrCode.Success});
    //     }).catch((err: any) => {
    //         this._errHandler(req, res, err);
    //     });
    // }
    //
    // private _actLogout(req: Request, res: Response) {
    //     req.session[Magics.SessUser] = null;
    //     delete req.session[Magics.SessUser];
    //     res.redirect('/');
    // }
    //
    // private _actDoResetPwd(req: Request, res: Response) {
    //     let {password} = req.body;
    //     let sess = req.session[Magics.SessUser] || {};
    //     Promise.resolve().then(() => {
    //         if (!(sess && sess._id)) {
    //             return Promise.reject({err_code: ErrCode.UserNotLogin});
    //         }
    //         return;
    //     }).then(() => {
    //         res.send({err_code: ErrCode.Success});
    //     }).catch((err: any) => {
    //         this._errHandler(req, res, err);
    //     });
    // }

}